import React, { useEffect, useRef, useState } from 'react'
import { Tabs, Input, Button } from 'antd'
import request from '../../utils/index'
import Qrcode from 'qrcode'
import { useNavigate } from 'react-router-dom'
type Props = {}

const num = 60

const Index = (props: Props) => {
	const navigate = useNavigate()
	/*****************倒计时*****************/
	const [count, setCount] = useState(num)
	const [userCode, setUserCode] = useState('')
	const login = async () => {
		const resp = await request({ url: '/api/tel', data: { tel }, method: 'post' })
		const { code, data } = resp.data

		if (code === 200) {
			console.log(data);
			setUserCode(data)
			setCount(count - 1)
		}
	}

	const onLogin = async () => {
		const resp = await request({ url: '/api/tel/login', method: 'post', data: { userCode } })
		const { code } = resp.data
		if (code === 200) {
			navigate('/')
		}
	}
	useEffect(() => {
		if (count === num) {

		} else if (count === 0) {
			setCount(num)
		} else {
			setTimeout(() => {
				setCount(count - 1)
			}, 1000)
		}
	}, [count])

	/****************手机*****************/
	const [tel, setTel] = useState('')


	/****************二维码*****************/
	const img = useRef<HTMLImageElement>(null)

	useEffect(() => {
		Qrcode.toDataURL('扫一扫, 哈哈哈哈哈哈').then(url => {
			console.log(url);

			if (img.current) {
				console.log(111);

				img.current.src = url
			}
		})
	}, [])
	return (
		<div className='login'>
			<Tabs defaultActiveKey='2'>
				<Tabs.TabPane tab="手机号登录" key={1}>
					{tel}
					<Input type="text" value={tel} onChange={(e) => setTel(e.target.value)} />
					<Button block type='primary' disabled={count !== num} onClick={() => login()}>{count === num ? '获取验证码' : `距离再次获取还剩${count}秒`}</Button>
					<Button block type='primary' onClick={() => onLogin()}>登录</Button>
				</Tabs.TabPane>
				<Tabs.TabPane tab="二维码登录" key={2}>
					<img alt="" ref={img} width="300" height="300" />
				</Tabs.TabPane>
			</Tabs>
		</div>
	)
}

export default Index